/* === LICENSE INFO ===
 * This source file is subject to the GPLv3 license that is bundled with this
 * package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl.txt
 * === end of LICENSE INFO === */

#include <QtGui/QApplication>
#include "MainWindow.h"
#include "gUtil/GLog/GLog.hpp"
#include <iostream>

using namespace gUtil::GLog;

const std::string g_ModuleName = "NetCom Simulator (app_gui)";


bool init();

int main(int _argc, char* _argv[])
{
    int exitStatus = 1;
    if (!init())
    {
        std::cerr << "[EMERGENCY] A" << std::endl;
        return exitStatus;
    }

    GLog& logger = GLog::getInstance();
    logger.append(g_ModuleName + " is starting", GLog::LEVEL_INFO);

    try
    {
        QApplication a(_argc, _argv);
        MainWindow w;
        w.show();
        exitStatus = a.exec();

        logger.append(g_ModuleName + " is exiting", GLog::LEVEL_INFO);
        return exitStatus;
    }
    catch (std::exception& e)
    {
        // Log to std err as well in case logger already destroyed.
        std::cerr << "[EMERGENCY] main(): " << e.what() << std::endl;
        logger.append(e.what(), GLog::LEVEL_EMERGENCY);
        logger.append("main(): Application exits now.", GLog::LEVEL_EMERGENCY);
    }
    catch (...)
    {
        // Log to std err as well in case logger already destroyed.
        std::cerr << "[EMERGENCY] main(): Unknown exception detected." <<
                std::endl;
        logger.append("main(): Unknown exception detected.",
                GLog::LEVEL_EMERGENCY);
        logger.append("main(): Application exits now.", GLog::LEVEL_EMERGENCY);
    }
    
    return exitStatus;
}


bool init()
{
    bool initStatus = true;

    try
    {
        // Init logger
        GLog::setLogId("NetCom");
        GLog::setMaxLogLevel(GLog::LEVEL_DEBUG);
        GLog::addOutputType(LogWriterManager::OUTPUT_FILE);
        GLog::initConfig();
    }
    catch (std::exception& e)
    {
        // Allow app to run without logger
        std::cerr << "[CRITICAL] main.cpp: Logger init failed [" << e.what() <<
                "]" << std::endl;
    }

    return initStatus;
}
